package com.aisile.common.exception;

import com.aisile.model.common.dtos.ResponseResult;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.ConnectException;
import java.sql.SQLException;

/**
 * @Auther:yry
 * @Date:2023/12/22 0022
 * @VERSON:1.0
 */
@Slf4j
@ControllerAdvice
//@RestControllerAdvice
public class ExceptionCatch {

    // key exception  value = ResponseResult.errorResult(99999,"遇到不可预知异常了，请联系管理员")
    public static ImmutableMap<Class<? extends Exception>,ResponseResult> EXCEPTIONS;
    public static ImmutableMap.Builder<Class<? extends Exception>,ResponseResult> builder = ImmutableMap.builder();

    static {
        // 空指针
        builder.put(NullPointerException.class,ResponseResult.errorResult(30000,"数据是空的，整不了"));
        builder.put(IndexOutOfBoundsException.class,ResponseResult.errorResult(30001,"下标超越限制了"));
        builder.put(NumberFormatException.class,ResponseResult.errorResult(30002,"需要数值数据，转换失败"));
        builder.put(ArithmeticException.class,ResponseResult.errorResult(30003,"运算、计算出现错误"));
        builder.put(SQLException.class,ResponseResult.errorResult(30004,"底层SQL出现问题"));
        builder.put(ConnectException.class,ResponseResult.errorResult(30005,"连接不上...."));
        builder.put(HttpMessageNotReadableException.class,ResponseResult.errorResult(30006,"请求参数不合法"));
    }


    // 不可预知异常处理
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public ResponseResult NotCustomException(Exception e){
        //处理异常
        e.printStackTrace();
        log.debug(e.toString());
        if(EXCEPTIONS == null){
            EXCEPTIONS = builder.build();
        }
        ResponseResult responseResult =  EXCEPTIONS.get(e.getClass());
        if(responseResult==null){
            return ResponseResult.errorResult(99999,"遇到不可预知异常了，请联系管理员");
        }
        return responseResult;
    }

    // 可预知异常处理
    @ExceptionHandler(value = {CustomException.class})
    @ResponseBody
    public ResponseResult CustomException(CustomException e){
        e.printStackTrace();
        // new
        builder.build();
        //处理异常
        log.debug(e.toString());
        return e.getResponseResult();
    }

}
